package com.yaorange.teaching.service.impl;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.yaorange.teaching.service.AIService;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Arrays;

/**
 * @author coach tam
 * @email 327395128@qq.com
 * @values 坚持灵活 灵活坚持
 * @since 2024/11/25
 */
@Slf4j
@Primary
@Service("dashScope")
public class DashScopeAIServiceImpl implements AIService {

    public static final String QWEN_TURBO = "qwen-turbo";
    public static final String API_KEY = "sk-ac8c6b063f834d0d8b9934ed0089833a";

    @Override
    public Flux<String> checkAnswer(String question, String answer) {
        Flux<String> result = null;
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("请评估以下面试题的回答情况，给出评分，评分规则是0至10分的评分，0为非常差，10为满分。问题是:"+question+"  答案是:"+answer+"。整体返回的文本内容只能包含建议和评分，整体返回的文本格式为: 建议:xxx; \n  评分:x分。").build();
            result= streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            log.error("检查答案异常: {}", e.getMessage());
        }
        return result;
    }

    public static Flux<String> streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        Flowable<GenerationResult> result = gen.streamCall(param);
        //将Flowable 转成 flux
        return Flux.from(result).map(message -> message.getOutput().getChoices().get(0).getMessage().getContent());
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                .model(QWEN_TURBO)
                .apiKey(API_KEY)
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .topP(0.8)
                .incrementalOutput(true)
                .build();
    }
}
